﻿using System.IO;
using System.Linq;
using System.Modules.Constants;
using System.Text.RegularExpressions;

namespace System.Modules.Extensions
{
    /// <summary>
    /// String Builder Extensions
    /// </summary>
    public static class StringBuilderExtensions
    {
        #region Fix Html Image Src
        /// <summary>
        /// Use this method to replace HTML image source with a prefix.
        /// </summary>
        /// <param name="htmlText"></param>
        /// <param name="urlPrefix"></param>
        /// <returns></returns>
        public static System.Text.StringBuilder FixHtmlImageSrc(this System.Text.StringBuilder htmlText, string urlPrefix)
        {
            //Change the relative URL's to absolute URL's for an image, if any in the HTML code.
            foreach (var match in Regex.Matches(htmlText.ToString(), RegularExpressionPatterns.IMAGE_PATTERN, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.RightToLeft).Cast<Match>().Where(match => match.Success))
            {
                htmlText.Replace(match.Value, new System.Text.StringBuilder(urlPrefix).Append(Path.GetFileName(match.Value).RemoveIllegalFileNameCharachters()).ToString());
            }
            return htmlText;
        }
        #endregion

        #region Validate Html Href
        /// <summary>
        /// Use this method to validate HTML Href for valid URL.
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public static System.Text.StringBuilder ValidateHtmlHref(this System.Text.StringBuilder htmlText)
        {
            //Change the relative URL's to absolute URL's for an image, if any in the HTML code.
            foreach (var match in from Match match in Regex.Matches(htmlText.ToString(), RegularExpressionPatterns.HREF_PATTERN, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.RightToLeft) where match.Success where !Uri.IsWellFormedUriString(match.Value, UriKind.RelativeOrAbsolute) select match)
            {
                htmlText.Replace(match.Value, string.Empty);
            }
            return htmlText;
        }
        #endregion
    }
}